package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.dto.ProjectStageAddDTO;
import com.ruoyi.system.dto.ConstructionProjectStageDTO;
import com.ruoyi.system.entity.ConstructionProjectDO;
import com.ruoyi.system.entity.ConstructionStageDO;
import com.ruoyi.system.entity.ConstructionProjectStageRelDO;
import com.ruoyi.system.mapper.ConstructionStageMapper;
import com.ruoyi.system.mapper.ConstructionProjectStageRelMapper;
import com.ruoyi.system.service.ConstructionProjectService;
import com.ruoyi.system.service.ConstructionStageService;
import com.ruoyi.system.service.IConstructionItemService;
import com.ruoyi.system.service.IProjectStageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 项目阶段管理Service实现类
 */
@Service
public class ProjectStageServiceImpl extends ServiceImpl<ConstructionProjectStageRelMapper, ConstructionProjectStageRelDO> implements IProjectStageService {

    @Resource
    private ConstructionProjectStageRelMapper constructionProjectStageRelMapper;

    @Resource
    private ConstructionStageMapper constructionStageMapper;

    @Resource
    private ConstructionStageService constructionStageService;

    @Resource
    private ConstructionProjectService constructionProjectService;

    @Resource
    private IConstructionItemService projectItemService;

    @Override
    public List<ConstructionProjectStageDTO> getStagesByProjectId(Long projectId) {
        if (projectId == null) {
            throw new ServiceException("项目ID不能为空");
        }

        // 查询项目关联的所有阶段
        List<ConstructionProjectStageRelDO> relList = constructionProjectStageRelMapper.selectList(
                new LambdaQueryWrapper<ConstructionProjectStageRelDO>()
                        .eq(ConstructionProjectStageRelDO::getProjectId, projectId)
                        .eq(ConstructionProjectStageRelDO::getIsDeleted, 0)
        );

        if (relList.isEmpty()) {
            return Collections.emptyList();
        }

        List<Long> collect = relList.stream().map(ConstructionProjectStageRelDO::getStageId).distinct().collect(Collectors.toList());

        List<ConstructionStageDO> list = constructionStageService.lambdaQuery()
                .in(ConstructionStageDO::getId, collect)
                .list();

        Map<Long, String> stageMap = list.stream().collect(Collectors.toMap(ConstructionStageDO::getId, ConstructionStageDO::getStageName));

        // 转换为DTO并补充阶段信息
        return relList.stream().map(rel -> {
            ConstructionProjectStageDTO dto = new ConstructionProjectStageDTO();
            dto.setId(rel.getId());
            dto.setProjectId(rel.getProjectId());
            dto.setStageId(rel.getStageId());
            dto.setStageStatus(rel.getStageStatus());
            dto.setCreateTime(rel.getCreateTime());
            dto.setUpdateTime(rel.getUpdateTime());
            dto.setTeamName(rel.getTeamName());
            dto.setLeaderName(rel.getLeaderName());
            dto.setLeaderPhone(rel.getLeaderPhone());
            dto.setStageName(stageMap.get(rel.getStageId()));
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addStage(ProjectStageAddDTO stageAddDTO) {

        if (stageAddDTO.getStageId() == null || stageAddDTO.getProjectId() == null) {
            throw new ServiceException("项目ID、阶段ID不能为空");

        }

        ConstructionStageDO one = constructionStageService.lambdaQuery().eq(ConstructionStageDO::getId, stageAddDTO.getStageId())
                .eq(ConstructionStageDO::getIsDeleted, 0).one();
        if (one == null) {
            throw new ServiceException("所选阶段不存在或已被删除");
        }
        // 检查阶段是否已关联项目
        int count = constructionProjectStageRelMapper.selectCount(
                new LambdaQueryWrapper<ConstructionProjectStageRelDO>()
                        .eq(ConstructionProjectStageRelDO::getProjectId, stageAddDTO.getProjectId())
                        .eq(ConstructionProjectStageRelDO::getStageId, stageAddDTO.getStageId())
                        .eq(ConstructionProjectStageRelDO::getIsDeleted, 0)
        ).intValue();

        if (count > 0) {
            throw new ServiceException("该阶段已关联项目，不能重复添加");
        }

        // 保存项目-阶段关联关系
        ConstructionProjectStageRelDO rel = new ConstructionProjectStageRelDO();
        rel.setProjectId(stageAddDTO.getProjectId());
        rel.setStageId(stageAddDTO.getStageId());
        rel.setStageStatus(0); // 默认为未开始状态
        rel.setIsDeleted(0);
        rel.setCreateTime(LocalDateTime.now());
        rel.setTeamName(stageAddDTO.getTeamName());
        rel.setLeaderName(stageAddDTO.getLeaderName());
        rel.setLeaderPhone(stageAddDTO.getLeaderPhone());

        return constructionProjectStageRelMapper.insert(rel) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteStage(Long projectId, Long stageId) {
        if (projectId == null || stageId == null) {
            throw new ServiceException("项目ID和阶段ID不能为空");
        }

        // 检查阶段是否有未完成事项
        if (projectItemService.hasUnfinishedItems(projectId, stageId)) {
            throw new ServiceException("该阶段存在未完成事项，无法删除");
        }

        // 查询当前阶段信息
        ConstructionProjectStageRelDO rel = constructionProjectStageRelMapper.selectOne(
                new LambdaQueryWrapper<ConstructionProjectStageRelDO>()
                        .eq(ConstructionProjectStageRelDO::getProjectId, projectId)
                        .eq(ConstructionProjectStageRelDO::getStageId, stageId)
                        .eq(ConstructionProjectStageRelDO::getIsDeleted, 0)
        );

        if (rel == null) {
            throw new ServiceException("阶段不存在或已被删除");
        }

        rel.setUpdateTime(LocalDateTime.now());
        return constructionProjectStageRelMapper.deleteById(rel) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean bindTeamToStage(Long stageId, Long teamId, Long leaderId, String leaderPhone) {
        if (stageId == null) {
            throw new ServiceException("阶段ID不能为空");
        }

        // 这里需要根据实际的数据模型来实现绑定团队的逻辑
        // 假设阶段与团队的关联信息保存在ProjectStageRelDO中或其他关联表中
        ConstructionProjectStageRelDO rel = constructionProjectStageRelMapper.selectById(stageId);
        if (rel == null) {
            throw new ServiceException("阶段不存在");
        }

        // TODO: 实现绑定团队的逻辑，可能需要更新关联表或添加新的关联记录

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeStageStatus(Long projectId, Long stageId, Integer status) {
        if (projectId == null || stageId == null || status == null) {
            throw new ServiceException("参数不能为空");
        }

        if (status < 0 || status > 2) {
            throw new ServiceException("状态值无效");
        }

        ConstructionProjectStageRelDO rel = constructionProjectStageRelMapper.selectOne(
                new LambdaQueryWrapper<ConstructionProjectStageRelDO>()
                        .eq(ConstructionProjectStageRelDO::getProjectId, projectId)
                        .eq(ConstructionProjectStageRelDO::getStageId, stageId)
                        .eq(ConstructionProjectStageRelDO::getIsDeleted, 0)
        );

        if (rel == null) {
            throw new ServiceException("阶段不存在");
        }

        // 如果要将阶段标记为已完成，检查是否有未完成事项
        if (status == 2 && projectItemService.hasUnfinishedItems(projectId, stageId)) {
            throw new ServiceException("该阶段存在未完成事项，无法标记为已完成");
        }

        // 如果当前阶段变为进行中，将其他进行中的阶段变为未开始
        if (status == 1) {
            List<ConstructionProjectStageRelDO> otherStages = constructionProjectStageRelMapper.selectList(
                    new LambdaQueryWrapper<ConstructionProjectStageRelDO>()
                            .eq(ConstructionProjectStageRelDO::getProjectId, projectId)
                            .ne(ConstructionProjectStageRelDO::getStageId, stageId)
                            .eq(ConstructionProjectStageRelDO::getStageStatus, 1)
                            .eq(ConstructionProjectStageRelDO::getIsDeleted, 0)
            );

            otherStages.forEach(otherStage -> {
                otherStage.setStageStatus(0);
                otherStage.setUpdateTime(LocalDateTime.now());
                constructionProjectStageRelMapper.updateById(otherStage);
            });
        }

        rel.setStageStatus(status);
        rel.setUpdateTime(LocalDateTime.now());
        return constructionProjectStageRelMapper.updateById(rel) > 0;
    }

    @Override
    public ConstructionProjectStageDTO getCurrentStage(Long projectId) {
        if (projectId == null) {
            throw new ServiceException("项目ID不能为空");
        }

        ConstructionProjectStageRelDO currentRel = constructionProjectStageRelMapper.getCurrentStage(projectId);
        if (currentRel == null) {
            return null;
        }

        ConstructionProjectStageDTO dto = new ConstructionProjectStageDTO();
        dto.setId(currentRel.getId());
        dto.setProjectId(currentRel.getProjectId());
        dto.setStageId(currentRel.getStageId());
        dto.setStageStatus(currentRel.getStageStatus());
        dto.setCreateTime(currentRel.getCreateTime());
        dto.setUpdateTime(currentRel.getUpdateTime());

        // 查询阶段名称
        ConstructionStageDO stage = constructionStageMapper.selectById(currentRel.getStageId());
        if (stage != null) {
            dto.setStageName(stage.getStageName());
            // 补充团队和负责人信息
        }

        return dto;
    }


    @Override
    public List<ConstructionProjectDO> getProjectsByStageId(Long stageId) {
        List<ConstructionProjectStageRelDO> list = this.lambdaQuery()
                .eq(ConstructionProjectStageRelDO::getStageId, stageId)
                .eq(ConstructionProjectStageRelDO::getIsDeleted, 0)
                .list();
        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        List<Long> projectIds = list.stream().map(ConstructionProjectStageRelDO::getProjectId).distinct().collect(Collectors.toList());
        return constructionProjectService.lambdaQuery()
                .in(ConstructionProjectDO::getId, projectIds)
                .list();
    }

    @Override
    public List<ConstructionProjectDO> getUnlinkedProjectsByStageId(Long stageId) {
        List<ConstructionProjectDO> projects = constructionProjectService.lambdaQuery()
                .eq(ConstructionProjectDO::getIsDeleted, 0)
                .in(ConstructionProjectDO::getProjectStatus, 1, 2)
                .list();
        if (projects.isEmpty()) {
            return Collections.emptyList();
        }

        List<ConstructionProjectStageRelDO> rels = this.lambdaQuery()
                .eq(ConstructionProjectStageRelDO::getStageId, stageId)
                .eq(ConstructionProjectStageRelDO::getIsDeleted, 0)
                // 如“已完成”也算已关联，则删掉下一行
                //.ne(ConstructionProjectStageRelDO::getStageStatus, 2)
                .list();

        if (!rels.isEmpty()) { // 关键修复：使用本地变量
            List<Long> linkedIds = rels.stream()
                    .map(ConstructionProjectStageRelDO::getProjectId)
                    .distinct()
                    .collect(Collectors.toList());
            projects = projects.stream()
                    .filter(p -> !linkedIds.contains(p.getId()))
                    .collect(Collectors.toList());
        }
        return projects;
    }
}